package cn.woblog.android.http;

import android.os.AsyncTask;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import cn.woblog.android.common.utils.Const;
import cn.woblog.android.common.utils.NetworkUtils;
import cn.woblog.android.http.cache.CacheControl;
import cn.woblog.android.http.callback.AbstractCallback;
import cn.woblog.android.http.callback.ICallback;

public class RequestTask<T> extends AsyncTask<Void, Integer, Object[]> {
	private Request request;
	private AbstractCallback<T> callback;
	private String tag;
	private OkHttpClient client;

	public RequestTask(OkHttpClient client, Request request, ICallback<T> callback, String tag) {
		this.client = client;
		this.request = request;
		this.callback = (AbstractCallback<T>) callback;
		this.tag = tag;
	}

	@Override
	protected Object[] doInBackground(Void... params) {
		return sendRequest();
	}

	private Object[] sendRequest() {
		Object[] result = new Object[2];
		T preRequest = callback.preRequest();
		if (preRequest != null) {
			result[0] = preRequest;
			result[1] = null;
			return result;
		}
		Call value = client.newCall(request);
		Http.addCache(tag, value);
		try {
			if (callback.isCache() && !NetworkUtils.isNetworkAvailable(Http.getContext())) {
				CacheControl cacheControl = Http.getCacheControl();
				String cacheString = cacheControl.getCacheString(request.urlString(), callback.getCacheKey());
				if (cacheString != null) {
					T bindData = callback.bindData(cacheString, this);
					result[0] = bindData;
					result[1] = null;
					Http.getHandler().obtainMessage(Const.MSG_SHOW_OFFLINE_INFO).sendToTarget();
				} else {
					result[0] = null;
					result[1] = new AppException("The network is not available and get cache is null");
				}
			} else {
				Response response = value.execute();
				T bindData = callback.bindData(response, request, this);
				bindData = callback.postRequest(bindData);
				if (response.isSuccessful()) {
					result[0] = bindData;
					result[1] = response;
				} else {
					result[0] = null;
					result[1] = new AppException(response.message(), response.code());
				}
			}

			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result[0] = null;
			result[1] = new AppException(e);
		}
		return result;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
	}

	@Override
	protected void onPostExecute(Object[] result) {
		Http.removeCall(tag);
		if (result[0] == null) {
			//			if (result[1] != null&& result[1]) {
			//
			//			}
			callback.onFailure(request, (AppException) result[1]);
		} else {
			callback.onSuccess((Response) result[1], (T) result[0]);
		}
		super.onPostExecute(result);
	}

}
